/**    
 * @{#} PatientCommonDataChooseActivity.java Create on 2014-7-2 下午2:48:48    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import cn.o.app.json.JsonUtil;
import cn.skinapp.R;

import com.alipay.sdk.util.JsonUtils;
import com.evan.common.adapter.BaseAdapter;
import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.task.RequestTask;
import com.evan.common.utils.CacheCommon;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.SymptomPatientTask.SymptomItemInfo;
import com.smiier.skin.net.SymptomPatientTask.SymptomPatientItem;
import com.smiier.skin.net.SymptomPatientTask.SymptomPatientResponse;
import com.smiier.skin.net.entity.User;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.umeng.analytics.MobclickAgent;

public class CommonDataChooseActivity extends BasicActivity implements
		OnItemClickListener {

	ListView list_common_data;
	PatientCommonDataAdapter adapter;

	private String url, title, param, type, choose, data_type;

	private HashMap<String, String> values = new HashMap<String, String>();

	public static final String TYPE_URL = "url", TYPE_FIXATION = "fixation",
			MULITCHOOSE = "mulitchoose", SINGLECHOOSE = "singlechoose";

	public static String DATA_TYPE_SEX = "SEX", DATA_TYPE_MARRY = "MARRY",
			DATA_TYPE_HUAIYUN = "HUAIYUN";

	// isChoose标识是否是选择返回作为条件，见DoctorActivity
	private boolean isChoose = false;
	private String province_city_country;

	private EditText edit_search;
	JSONArray array;
	private int maxSize;
private  String mSelectText;
	private boolean isBingli = false;
	ArrayList<SymptomPatientItem> Symptoms = new ArrayList<SymptomPatientItem>();
boolean mInit = true ;
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_common_data_choose);

		init();

		list_common_data = (ListView) findViewById(R.id.list_common_data);

		isChoose = getIntent().getBooleanExtra(Constant.IDENTITY_KEY_1, false);
		mSelectText = getIntent().getStringExtra(Constant.IDENTITY_KEY_2);
		if(mSelectText!=null&&!mSelectText.equals("")){
			values.put(mSelectText, mSelectText);
		}
		isBingli = getIntent().getBooleanExtra(Constant.IDENTITY_KEY_BINGLI,
				false);
		province_city_country = getIntent().getStringExtra(
				Constant.IDENTITY_KEY_PROVINCE_CITY_COUNTRY);
		maxSize = getIntent()
				.getIntExtra(Constant.IDENTITY_KEY_ITEM_SIZE, 1000);

		String[] datas = getIntent().getStringArrayExtra(Constant.IDENTITY_KEY);
		url = datas[0];
		title = datas[1];
		param = datas[2];
		type = datas[3];
		choose = datas[4];
		data_type = datas[5];

		if (!isChoose) {
			setNavRightBtn("保存");
		} else {
			setNavRightBtn("确定");
		}

		setNavTitle(title);

		View headView = LayoutInflater.from(activity).inflate(
				R.layout.view_search, null);
		edit_search = (EditText) headView.findViewById(R.id.edit_search);
		if (!param.equals("Sex") && !param.equals("Hospital")) {

			// list_common_data.addHeaderView(headView);
		}

		if (!CommonUtility.isNull(type)) {
			if (type.equals(TYPE_URL)) {
				ArrayList<CacheCommon> caches = dbUtil.queryCache(param);
				if (caches.size() > 0) {
					String data = caches.get(0).data;
					try {
						array = new JSONArray(data);
						if (param.equals("Bank")) {
							JSONArray symptoms = new JSONArray();
							for (int i = 0; i < array.length(); i++) {
								symptoms.put(array.getJSONObject(i).getString(
										"Name"));
							}

							array = symptoms;
						} else if (param.equals("Skilled")) {
							String str = CommonUtility.getStringToBean(
									Symptoms, "Symptom_Patient.txt",
									getContext());
							try {
								Symptoms = JsonUtil.convert(str,
										SymptomPatientResponse.class);
								ArrayList<String> tmp = new ArrayList<String>();
								for (SymptomPatientItem item : Symptoms) {
									ArrayList<SymptomItemInfo> Symptoms = item.Symptoms;
									for (SymptomItemInfo info : Symptoms) {
										tmp.add(info.Doctor_Name);
									}
								}
								array = JsonUtil.convertToArray(tmp);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						o();
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					if (param.equals("Skilled")) {
						
						String str = CommonUtility.getStringToBean(
								Symptoms, "Symptom_Patient.txt",
								getContext());
						try {
							Symptoms = JsonUtil.convert(str,
									SymptomPatientResponse.class);
							ArrayList<String> tmp = new ArrayList<String>();
							for (SymptomPatientItem item : Symptoms) {
								ArrayList<SymptomItemInfo> Symptoms = item.Symptoms;
								for (SymptomItemInfo info : Symptoms) {
									tmp.add(info.Doctor_Name);
								}
							}
							array = JsonUtil.convertToArray(tmp);
						} catch (Exception e) {
							e.printStackTrace();
						}
						
						o();

					} else {
						new RequestTask(activity, url, new RequestHandler(activity,
								new HandlerCallback() {

									@Override
									public void callback(Object o) {
										if (!CommonUtility.isNull(o)) {
											try {
												array = new JSONArray(o.toString());
												if (url.equals(Constant.URL.REQUEST_SYMPTOM_JSON)
														|| url.equals(Constant.URL.REQUEST_BANK_JSON)) {
													JSONArray symptoms = new JSONArray();
													for (int i = 0; i < array
															.length(); i++) {
														symptoms.put(array
																.getJSONObject(i)
																.getString("Name"));
													}
													array = symptoms;
												}
												o();
												dbUtil.saveOrUpdate(param, o);
											} catch (Exception e) {
												e.printStackTrace();
											}
										}
									}
								}), RequestTask.CHAR).execute();

					}

				}
			} else if (type.equals(TYPE_FIXATION)) {
				try {
					array = new JSONArray(url);
					o();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		edit_search.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence text, int arg1, int arg2,
					int arg3) {
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable edit) {
				if (!CommonUtility.isNull(array) && array.length() > 0) {
					JSONArray filterArray = new JSONArray();
					for (int i = 0; i < array.length(); i++) {
						try {
							String value = array.getString(i);
							if (!CommonUtility.isNull(value)
									&& value.indexOf(edit.toString()) != -1) {
								filterArray.put(value);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					adapter.notifyUpdate(filterArray);
				}
			}
		});
	}

	void o() {

		List<String> data = new ArrayList<String>();

		JSONArray xxx = new JSONArray();

		try {

			for (int i = 0; i < array.length(); i++) {
				if (data.isEmpty()) {
					data.add(array.getString(i));

					xxx.put((Object) array.getString(i));
				} else {

					if (!data.contains(array.getString(i))) {
						data.add(array.getString(i));
						xxx.put((Object) array.getString(i));
					}
				}

			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		adapter = new PatientCommonDataAdapter(activity, xxx);
		list_common_data.setAdapter(adapter);
		list_common_data.setOnItemClickListener(CommonDataChooseActivity.this);
	}

	public void onClick(View view) {
		super.onClick(view);
		int id = view.getId();
		if (id == R.id.text_right) {
			if (values.size() <= maxSize) {
				StringBuilder sb = new StringBuilder();
				for (String value : values.values()) {
					sb.append(value).append(",");
				}
				String content = CommonUtility.isNull(sb) ? sb.toString() : sb
						.substring(0, sb.lastIndexOf(","));
				if (isChoose) {
					Intent data = new Intent();
					if (param.equals("Hospital")) {
						try {
							JSONObject obj = new JSONObject(content);
							content = obj.getString("Name");
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}
					data.putExtra(Constant.IDENTITY_KEY, content);
					data.putExtra(Constant.IDENTITY_KEY_1, param);
					setResult(0, data);
					finish();
				} else {
					HashMap<String, Object> params = new HashMap<String, Object>();
					if (!CommonUtility.isNull(data_type)) {
						if (data_type.equals(DATA_TYPE_SEX)) {
							content = CommonUtility.convertString2Index(
									content, CommonUtility.sex) + "";
						} else if (data_type.equals(DATA_TYPE_MARRY)) {
							content = CommonUtility.convertString2Index(
									content, CommonUtility.marry) + "";
						} else if (data_type.equals(DATA_TYPE_HUAIYUN)) {
							content = CommonUtility.convertString2Index(
									content, CommonUtility.huaiyun) + "";
						}
					}
					// 标识是否为居住地或者医院
					if (!CommonUtility.isNull(province_city_country)) {
						String[] ps = param.split(Constant.SPLIT);
						String[] values = province_city_country
								.split(Constant.SPLIT);
						params.put(ps[0], values[0]);
						params.put(ps[1], values[1]);
						params.put(ps[2], content);
					} else {
						if (param.equals("Hospital")) {
							try {
								JSONObject obj = new JSONObject(content);
								content = obj.getString("Name");
								params.put(param, content);
							} catch (JSONException e) {
								e.printStackTrace();
							}

						} else {
							params.put(param, content);
						}

					}
					if (isBingli) {
						params.put(Constant.PARAM_API, "MR.User.Set");
						if (!CommonUtility.isNull(GlobalSettings.sBingLi)) {
							try {
								params.put("MRUID", GlobalSettings.sBingLi.Uid);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					} else {
						params.put(Constant.PARAM_API, "User.Set");
					}
					params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
					RequestTaskIntercept.requestIntercept(activity,
							Constant.URL.REQUEST, new RequestHandler(activity,
									new HandlerCallback() {

										@Override
										public void callback(Object o) {
											if (!CommonUtility.isNull(o)) {
												JSONObject object = (JSONObject) o;
												try {
													int resultCode = object
															.getInt(Constant.JSON_PARAM_RESCODE);
													if (CommonUtility
															.response200(object)) {
														CommonUtility.toast(
																activity,
																"保存成功");
														try {
															if (isBingli) {
																GlobalSettings.sBingLi = JsonUtil
																		.convertFromObject(
																				object.getJSONObject("Res"),
																				User.class);
															} else {
																GlobalSettings.sUser = JsonUtil
																		.convertFromObject(
																				object.getJSONObject("Res"),
																				User.class);
															}
															finish();
														} catch (Exception e) {
															e.printStackTrace();
														}
													} else if (resultCode == -2005) {
														CommonUtility
																.tip(activity,
																		"您已经认证或者正在等待审核认证中，不可修改数据。");
													} else {
														CommonUtility.tip(
																activity,
																"修改失败，请稍后再试。");
													}
												} catch (Exception e) {
													e.printStackTrace();
												}
											}
										}
									}), params);
				}
			} else {
				CommonUtility.tip(activity, "选择项不能超过" + maxSize + "个");
			}
		} else if (id == R.id.btn_clear) {
			edit_search.setText(null);
		}
	}

	CheckBox preCheckBox;

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int arg2,
			long arg3) {
		CheckBox checkBox = (CheckBox) view.getTag();
		if (!CommonUtility.isNull(checkBox)) {
			String text = (String) checkBox.getTag();
			if(param.equals("Sex")){
				if(checkBox.isChecked()){
					checkBox.setChecked(true);
					return;
				}
			}
			boolean isCheck = checkBox.isChecked();
			checkBox.setChecked(!isCheck);
			if (!isCheck) {
				values.put(text, text);
			} else {
				values.remove(text);
			}
		}
		if (!CommonUtility.isNull(choose) && choose.equals(SINGLECHOOSE)
				&& !CommonUtility.isNull(preCheckBox)
				&& preCheckBox != checkBox) {
			preCheckBox.setChecked(false);
			values.remove((String) preCheckBox.getTag());
		}
		preCheckBox = checkBox;
	}

	public class PatientCommonDataAdapter extends BaseAdapter {

		public PatientCommonDataAdapter(Activity activity, JSONArray array) {
			super(activity, array);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = views[position];
			if (!CommonUtility.isNull(convertView)) {
				return convertView;
			}
			String text = (String) getItem(position);
			convertView = inflater.inflate(R.layout.item_common_data, null);
			CheckBox checkBox = (CheckBox) convertView
					.findViewById(R.id.check_common);
			checkBox.setTag(text);
			convertView.setTag(checkBox);
			TextView name = (TextView) convertView.findViewById(R.id.text_name);
			if (param.equals("Hospital")) {
				try {
					JSONObject obj = new JSONObject(text);
					name.setText(obj.getString("Name"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else {
				if(mInit){
					if(mSelectText!=null&&!mSelectText.trim().equals("")&&mSelectText.equals(text)){
						checkBox.setChecked(true);
						checkBox.setTag(mSelectText);
						preCheckBox = checkBox;
						mInit = false;
					}
				}
				name.setText(text);
			}
			return convertView;
		}

		@Override
		public Object getItem(int position) {
			try {
				return array.getString(position);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

	}

	/*
	 * @Override public void onResume() { super.onResume();
	 * MobclickAgent.onResume(getContext()); }
	 * 
	 * @Override public void onPause() { super.onPause();
	 * MobclickAgent.onPause(getContext()); }
	 */

}
